<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\exception\ValidateException;

use app\common\model\{Reimburse, Img};
use app\common\validate\{ReimburseValidate};

class ReimburseController extends BaseController
{
    private $reimburseModel;

    public function __construct(Reimburse $reimburseModel)
    {
        parent::initialize();
        $this->reimburseModel = $reimburseModel;
    }

    /** 新增报销 */
    public function add()
    {
        $data = input('');

        try{
            validate(ReimburseValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $data['submit_time'] = strtotime($data['submit_time']);

        $addFlag = $this->reimburseModel->add($data);

        if($addFlag['code'] != 'ok'){
            $this->error_back($addFlag['msg']);
        }

        $imgs = json_decode($data['imgs'], true);

        if(isset($imgs) && !empty($imgs)){
            $imgModel = new Img();

            $imgArr = [];
            foreach($imgs as $img){
                $imgArrInfo = [
                    'obj_id'   => $addFlag['data'],
                    'obj_type' => 1,
                    'type'     => 1,
                    'img'      => $img,
                ];

                $imgArr[] = $imgArrInfo;
            }

            $imgModel->addAll($imgArr);
        }

        $this->success_back('新增成功');
    }

    /** 报销列表 */
    public function list()
    {
        $data = input('');

        try{
            validate(ReimburseValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['user_id' , '=', $data['user_id']];
        
        if($data['type'] == 1){
            $where[] = ['status' , '=', 1];
        }else{
            $where[] = ['status' , '<>', 1];
        }

        $list = $this->reimburseModel->getList($where, 1, $data['page'], $data['limit'], '*', 'create_time DESC');

        if($list['code'] != 'ok'){
            $this->error_back($list['msg']);
        }

        $imgModel = new Img();

        foreach($list['data'] as &$v){
            $list_img = $imgModel->getList(['obj_id' => $v['id'], 'type' => 1], 0);

            if($list_img['code'] != 'ok'){
                $imgs = [];
            }else{
                $imgs_arr = $list_img['data']->toArray();
                $imgs = array_column($imgs_arr, 'img');
            }

            $v['img'] = $imgs;
        }

        $this->success_back('ok', $list['data']);
    }
}